<?php
class ChallengeController extends Controller {
	/**
	 *
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 *      using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public function actions() {
		return array (
				'connector' => array (
						'class' => 'ext.elFinder.ElFinderConnectorAction',
						'settings' => array (
								'root' => Yii::getPathOfAlias ( 'webroot' ) . '/uploads/',
								'URL' => Yii::app ()->baseUrl . '/uploads/',
								'rootAlias' => 'Home',
								'mimeDetect' => 'none' 
						) 
				) 
		);
	}
	public $layout = '//layouts/column3';
	
	/**
	 *
	 * @return array action filters
	 */
	public function filters() {
		return array (
				'accessControl'  // perform access control for CRUD operations
				);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * 
	 * @return array access control rules
	 */
	public function accessRules() {
		return array (
				array (
						'allow', // allow all users to perform 'index' and 'view' actions
						'actions' => array (
								'index',
								'view' 
						),
						'users' => array (
								'@' 
						) 
				),
				array (
						'allow', // allow authenticated user to perform 'create' and 'update' actions
						'actions' => array (
								'create',
								'update' 
						),
						'users' => array (
								'@' 
						) 
				),
				array (
						'allow', // allow admin user to perform 'admin' and 'delete' actions
						'actions' => array (
								'admin',
								'delete' 
						),
						'users' => array (
								'admin' 
						) 
				),
				array (
						'deny', // deny all users
						'users' => array (
								'*' 
						) 
				) 
		);
	}
	
	/**
	 * Displays a particular model.
	 * 
	 * @param integer $id
	 *        	the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->render ( 'view', array (
				'model' => $this->loadModel ( $id ) 
		) );
	}
	
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
		$model = new Challenge ();
		$proposal = new Proposal ();
		$content = new Content ();
		$sources = array ();
		
		// get the challenged list;
		
		$challenged = $this->verifyChallenged ();
		$hasContent = true;
		$hasSource = true;
		$areDifferent = true;
		
		// $this->performAjaxValidation($model);
		
		if (isset ( $_POST ['Challenge'] )) {
			
			$sources = $this->verifySources ( $sources );
			
			$hasContent = Utils::hasContent ( $challenged );
			$hasSource = Utils::hasContent ( $sources );
			
			date_default_timezone_set ( 'UTC' );
			
			// challenge
			$model->attributes = $_POST ['Challenge'];
			$model->challenger_id = $_SESSION ['user']->id;
			$model->begin_date = date ( 'Y-m-d H:i:s' );
			
			// proposal
			$proposal->attributes = $_POST ['Proposal'];
			$proposal->date = date ( 'Y-m-d H:i:s' );
			$proposal->user_id = $_SESSION ['user']->id;
			
			$model->name = $proposal->title;
			
			// content
			$content->attributes = $_POST ['Content'];
			$content->position = 1;
			$content->proposal_id = 0;
			$content->id = 0;
			
			if ($hasContent) {
				foreach ( $challenged as $chall ) {
					$areDifferent = $chall->id != 0 && $model->mediator_id != 0 && $chall->id != $model->mediator_id;
					if (! $areDifferent) {
						break;
					}
				}
			}
			
			if ($model->validate () && $proposal->validate () && $hasContent && $hasSource && $areDifferent) {
				$model->name = $proposal->title;
				
				// save model
				$model->save ();
				
				// save proposal
				$proposal->save ();
				
				$content->proposal_id = $proposal->id;
				$content->save ();
				
				$this->saveSources ( $sources, $proposal->id );
				
				// save Challenge has Proposal
				$this->saveProposalsByChallenger ( $model, $proposal, $challenged );
				
				// goes to new challenge view
				$this->redirect ( array (
						'view',
						'id' => $model->id 
				) );
			}
		}
		
		$this->render ( 'create', array (
				'model' => $model,
				'proposal' => $proposal,
				'challenged' => $challenged,
				'hasContent' => $hasContent,
				'hasSource' => $hasSource,
				'areDifferent' => $areDifferent,
				'content' => $content,
				'sources' => $sources 
		) );
	}
	private function verifySources($sources) {
		if (isset ( $_POST ['Source'] )) {
			foreach ( $_POST ['Source'] as $post ) {
				
				$source = new Source ();
				$source->attributes = $post;
				if (($source->url != null && trim ( $source->url ) != "") || ($source->title != null && trim ( $source->title != "" ))) {
					$sources [] = $source;
				}
			}
		}
		return $sources;
	}
	private function saveSources($sources, $idProposal) {
		foreach ( $sources as $source ) {
			$source->proposal_id = $idProposal;
			$source->save ();
		}
	}
	
	private function saveProposalsByChallenged($model, $proposal, $challenged) {
		
		$challengeHasProposal = new ChallengeHasProposal();
		$challengeHasProposal->challenge_id = $model->id;
		$challengeHasProposal->proposal_id = $proposal->id;
		$challengeHasProposal->challenged_id = $challenged->id;
		
		$challengeHasProposal->save();
	}
	
	private function saveProposalsByChallenger($model, $proposal, $challengedList) {
		$allChallenged = ChallengeHasProposal::model ()->findAllByAttributes ( array (
				'challenge_id' => $model->id 
		) );
		$reused = array ();
		foreach ( $challengedList as $challenged ) {
			$challengeHasProposal = ChallengeHasProposal::model ()->findByAttributes ( array (
					'challenge_id' => $model->id,
					'proposal_id' => $proposal->id,
					'challenged_id' => $challenged->id 
			) );
			
			if ($challengeHasProposal == null) {
				$challengeHasProposal = new ChallengeHasProposal ();
				$challengeHasProposal->challenge_id = $model->id;
				$challengeHasProposal->proposal_id = $proposal->id;
				$challengeHasProposal->challenged_id = $challenged->id;
				$challengeHasProposal->save ();
			} else {
				$reused [0] = $challengeHasProposal;
			}
		}
		
		foreach ( $allChallenged as $challenged ) {
			if (! in_array ( $challenged, $reused )) {
				$challenged->delete ();
			}
		}
	}
	private function verifyChallenged($challengeHasProposal = null) {
		$users = array ();
		if (! is_null ( $challengeHasProposal )) {
			foreach ( $challengeHasProposal as $challHasProp ) {
				$users [] = User::model ()->findByPk ( $challHasProp->challenged_id );
			}
		}
		if (isset ( $_POST ['arv'] )) {
			$testvar = $_POST ['arv'];
			$users = $this->getNamesFromString ( $testvar );
		}
		
		return $users;
	}
	public function getNamesFromString($string) {
		$rows = explode ( ',', $string );
		$users = array ();
		
		foreach ( $rows as $row ) {
			
			$user = User::model ()->findByAttributes ( array (
					'id' => $row 
			) );
			if ($user != null) {
				$users [] = $user;
			}
		}
		
		return $users;
	}
	private function deleteSources($proposalId) {
		Source::model ()->deleteAllByAttributes ( array (
				'proposal_id' => $proposalId 
		) );
	}
	public function verifyAnswer($model) {
		$challengedTime = ChallengeHasProposal::model ()->findAllByAttributes ( array (
				'challenge_id' => $model->id,
				'challenged_id' => $_SESSION ['user']->id 
		) );
		$not_contains_answer = true;
		
		foreach ( $model->challengeHasProposals as $challengeHasProposal ) {
			if ($challengeHasProposal->proposal->user->id == $_SESSION ['user']->id) {
				$not_contains_answer = false;
				break;
			}
		}
		$canAnswer = $_SESSION ['user']->id != $model->challenger->id && $_SESSION ['user']->id != $model->mediator->id && $challengedTime != null && $not_contains_answer;
		
		return $canAnswer;
	}
	public function showAnswer($challengeHasProposal) {
		echo '<table style="margin-top: 10px; margin-bottom:30px;">';
		echo '<tr>';
		echo getUserLayout ( $challengeHasProposal->proposal->user, $challengeHasProposal->proposal->user->level );
		$text = $challengeHasProposal->proposal->contents [0]->text;
		$title = $challengeHasProposal->proposal->title;
		echo '<td>';
		$title = $challengeHasProposal->proposal->title;
		$content = "<div style=\"border-radius:5px;background:#F6FCFA;padding:10px;\">" . '<table><tr>' . 
		"<h4 style=\"margin-left:10px;\">$title</h4>" . "<div style=\"background:#eeeeee;padding:10px; border-radius:5px;\">$text</div>" . '</table>';
		echo $content;
		echo '<p>Referências:</p>';
		$cont = 0;
		foreach($challengeHasProposal->proposal->sources as $source) {
			echo '<p>'.++$cont.' - '.$source->title .' link: '.$source->url.'</p>';
		}
		echo '</div>';
		echo '</td>';
		echo '</tr>';
		echo '</table>';
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * 
	 * @param integer $id
	 *        	the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		// verifying for redirect
		$model = Challenge::model ()->findByPk ( $id );
		$hasSource = true;
		if (! $this->verifyAnswer ( $model )) {
			$this->redirect ( array ('view','id' => $model->id ) );
		}

		$proposal = new Proposal ();
		$content = new Content ();
		$sources = array();
		
		if (isset ( $_POST ['Proposal'] )) {
			$sources = $this->verifySources ( $sources );
			$hasSource = Utils::hasContent ( $sources );
			date_default_timezone_set ( 'UTC' );
			
			// proposal
			$proposal->attributes = $_POST ['Proposal'];
			$proposal->date = date ( 'Y-m-d H:i:s' );
			$proposal->user_id = $_SESSION ['user']->id;
			
			// content
			$content->attributes = $_POST ['Content'];
			$content->position = 1;
			$content->proposal_id = 0;
			$content->id = 0;
			
			if ($proposal->validate () && $content->validate() && $hasSource) {
			
				// save proposal
				$proposal->save ();
			
				$content->proposal_id = $proposal->id;
				$content->save ();
			
				$this->saveSources ( $sources, $proposal->id );
			
				// save Challenge has Proposal
				$this->saveProposalsByChallenged ( $model, $proposal, $model->challenger);
			
				// goes to new challenge view
				$this->redirect ( array (	'view',	'id' => $model->id	) );
			}
			
			
		}
		
		$this->render ( 'update', array (
				'model' => $model,
				'proposal' => $proposal ,
				'content' => $content,
				'sources' => $sources,
				'hasSource' => $hasSource,
		) );
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * 
	 * @param integer $id
	 *        	the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if (Yii::app ()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel ( $id )->delete ();
			
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (! isset ( $_GET ['ajax'] ))
				$this->redirect ( isset ( $_POST ['returnUrl'] ) ? $_POST ['returnUrl'] : array (
						'admin' 
				) );
		} else
			throw new CHttpException ( 400, 'Invalid request. Please do not repeat this request again.' );
	}
	
	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider ( 'Challenge' );
		$this->render ( 'index', array (
				'dataProvider' => $dataProvider 
		) );
	}
	
	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Challenge ( 'search' );
		$model->unsetAttributes (); // clear any default values
		if (isset ( $_GET ['Challenge'] ))
			$model->attributes = $_GET ['Challenge'];
		
		$this->render ( 'admin', array (
				'model' => $model 
		) );
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * 
	 * @param
	 *        	integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Challenge::model ()->findByPk ( $id );
		if ($model === null)
			throw new CHttpException ( 404, 'The requested page does not exist.' );
		return $model;
	}
	
	/**
	 * Performs the AJAX validation.
	 * 
	 * @param
	 *        	CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset ( $_POST ['ajax'] ) && $_POST ['ajax'] === 'challenge-form') {
			echo CActiveForm::validate ( $model );
			Yii::app ()->end ();
		}
	}
}
